<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { Global } from "../../Global";
import { HttpHelper } from "../../lib/HttpHelper";
import { ElTable, ElForm } from 'element-plus';
import Pagination from '@/components/Pagination.vue';

const isLoading = ref(false);
const isBusy = ref(false);
const listDatas = ref(<any[]>[]);
const pageNumber = ref(1);
const servicePath = "/UserInfo";
const total = ref(0);
const formData = ref(<any>{});
var editingData: any;
const dialogFormVisible = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);
const formRef = ref<InstanceType<typeof ElForm>>();

const dialogGoogleVisible = ref(false);
const dialogGoogleCodeVisible = ref(false);
const googleFormData = ref(<any>{});
const googleDialogTitle = ref("");
const setupCode = ref();
const googleFormRef = ref<InstanceType<typeof ElForm>>();
const resetGoogleFormData = () => {
  googleFormData.value = {
    userid: 0,
    issuer: null,
  };
}

const searchData = reactive({
  PageSize:10,
  PageIndex:0
});

const googleRules = reactive({
  issuer: [
    { required: true, message: '请输入发行方', trigger: 'blur' }
  ]
});

const roleDatas = ref(<any[]>[]);

const rules = reactive({
  Name: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ]
})

onMounted(() => {
  bindList();
});

const refreshClick = () => {
  bindList();
}

const loadRoles = async (systemId:any) => {
  isLoading.value = true;
  try {
    roleDatas.value = JSON.parse(await HttpHelper.get(`${servicePath}/GetAllRoles`, {systemId}));
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;
  }
}

const bindList = async () => {
  isLoading.value = true;
  try {
    searchData.PageIndex = pageNumber.value - 1;
    var json = await HttpHelper.postJson(`${servicePath}/List`, searchData);

    var list = JSON.parse(json);

    total.value = list.Total;
    listDatas.value.splice(0, listDatas.value.length);
    listDatas.value.push(...list.Datas);

    if (listDatas.value.length == 0 && pageNumber.value > 1) {
      pageNumber.value--;
      bindList();
    }
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;
  }
}

const resetFormData = () => {
  formData.value = {
    Name: "",
    Type: 0,
    RoleIds: [],
  };
}

const addClick = () => {
  loadRoles(null);
  resetFormData();
  dialogFormVisible.value = true;
}

const editClick = (row: any) => {
  loadRoles(row.SystemId);
  resetFormData();
  for (var p in row) {
    formData.value[p] = row[p];
  }
  formData.value.RoleIds = JSON.parse(formData.value.RoleIds);
  editingData = row;
  dialogFormVisible.value = true;
}

const deleteClick = async () => {

  if (isLoading.value)
    return;

  if (multipleSelection.value.length == 0) {
    Global.showInfo("请选择需要删除的数据");
    return;
  }

  if (confirm("确定删除吗？")) {
    try {
      isLoading.value = true;
      var requestData = new FormData();
      multipleSelection.value.forEach(x => {
        requestData.append("ids", x.id);

      });
      await HttpHelper.postFormData(`${servicePath}/Delete`, requestData);
      multipleSelection.value.forEach(x => {
        var index = listDatas.value.findIndex(m => m == x);
        if (index >= 0) {
          listDatas.value.splice(index, 1);
        }

      });
      multipleTableRef.value?.clearSelection();
    } catch (error) {
      Global.showError(error);
    }
    finally {
      isLoading.value = false;
    }
  }
}

const handleSelectionChange = (selecteds: any[]) => {
  multipleSelection.value = selecteds;
}

const submitClick = async () => {
  try {
    await formRef.value?.validate();
  } catch (error) {
    return;
  }

  try {

    isBusy.value = true;

    var submitBody = JSON.parse(JSON.stringify(formData.value));
    submitBody.RoleIds = JSON.stringify(submitBody.RoleIds);

    if (formData.value.id) {
      var obj = JSON.parse(await HttpHelper.postJson(`${servicePath}/Modify`, submitBody));
      listDatas.value.splice(listDatas.value.indexOf(editingData), 1, obj);
    }
    else {
      formData.value = JSON.parse(await HttpHelper.postJson(`${servicePath}/Add`, submitBody));
      formData.value.Password = null;
      listDatas.value.splice(0, 0, formData.value);
    }
    dialogFormVisible.value = false;
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isBusy.value = false;

  }
}

const googleMenuClick = (command: any) => {
  googleDialogTitle.value = command.title;

  editingData = command;
  resetGoogleFormData();
  googleFormData.value.userid = editingData.id;

  if (editingData.index == 0) {
    dialogGoogleVisible.value = true;
    googleFormData.value.issuer = Global.Title.System;
  }
  else if (editingData.index == 1) {
    ShowUserGoogleKey();
  }
  else if (editingData.index == 2) {
    deleteGoogleKey();
  }
}

const ShowUserGoogleKey = async () => {

  isLoading.value = true;
  try {
    setupCode.value = JSON.parse(await HttpHelper.get(`${servicePath}/GetUserGoogleKey`, googleFormData.value));

    dialogGoogleCodeVisible.value = true;
    dialogGoogleVisible.value = false;

  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;

  }
}

const SetUserGoogleKey = async () => {
  try {
    await googleFormRef.value?.validate();
  } catch (error) {
    return;
  }

  isBusy.value = true;
  try {
    setupCode.value = JSON.parse(await HttpHelper.get(`${servicePath}/SetUserGoogleKey`, googleFormData.value));

    dialogGoogleCodeVisible.value = true;
    dialogGoogleVisible.value = false;
    listDatas.value.find(x => x.id == editingData.id).GoogleKey = "a";

  } catch (error) {
    Global.showError(error);
  }
  finally {
    isBusy.value = false;

  }
}

const deleteGoogleKey = async () => {
  if (!window.confirm("确定删除此用户的谷歌验证吗？"))
    return;

  isLoading.value = true;
  try {
    await HttpHelper.get(`${servicePath}/SetUserGoogleKey`, googleFormData.value);
    var item = listDatas.value.find(x => x.id == editingData.id);
    item.GoogleKey = null;
    item.IsBindedGoogle = false;

  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;

  }
}

const deleteBlackList= async (id:any) => {
  if (!window.confirm("确定删除此用户的登录黑名单吗？"))
    return;

  isLoading.value = true;
  try {
    await HttpHelper.get(`${servicePath}/ClearBlackList`, {id:id});
    var item = listDatas.value.find(x => x.id == id);
    item.IsInBlackList = !item.IsInBlackList;

  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;

  }
}
</script>
<template>
  <div class="page-view-main">
    <div style="padding: var(--page-padding);flex:1;min-height:0px;display: flex;flex-direction: column;">
      <div class="page-view-panel">
        <div style="display: flex;justify-content: end;margin-bottom: 10px;">
          <el-button-group class="ml-4">
            <el-button type="default" icon="Plus" @click="addClick">添加</el-button>
            <el-button type="default" icon="Refresh" @click="refreshClick">刷新</el-button>
            <el-button type="default" icon="Delete" @click="deleteClick">删除</el-button>
          </el-button-group>
        </div>

        <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="listDatas"
          cell-class-name="tb-cell" header-cell-class-name="tb-header-cell" table-layout="auto" v-loading="isLoading"
          style="flex:1;min-height:0px;">
          <el-table-column type="selection" width="42" fixed="left" />
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="Name" label="用户名" />
          <el-table-column prop="Type" label="类型">
            <template #default="scope">
              <template v-if="scope.row.Type == 65792">超级管理员</template>
              <template v-else-if="scope.row.Type == 256">管理员</template>
              <template v-else>普通用户</template>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-button v-if="scope.row.IsInBlackList" size="small" @click="deleteBlackList(scope.row.id)" type="danger">删除登录黑名单</el-button>
              <el-tag v-else type="info" effect="light">正常</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="Role" label="角色" />
          <el-table-column prop="SystemId" label="所属系统ID" />
          <el-table-column prop="Owner" label="创建人" />
          <el-table-column prop="CreateTime" label="创建时间" :formatter="Global.formatUTCToLocal" />
          <el-table-column prop="UpdateTime" label="更新时间" :formatter="Global.formatUTCToLocal" />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editClick(scope.row)">
                编辑
              </el-button>
              <el-dropdown @command="googleMenuClick" trigger="click" style="margin-left: 10px;">
                <el-button size="small" v-if="scope.row.IsBindedGoogle" type="success">
                  谷歌验证码<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <el-button size="small" v-else-if="scope.row.GoogleKey" type="warning">
                  谷歌验证码<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <el-button size="small" v-else type="info">
                  谷歌验证码<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      :command="{ title: '开启、更换绑定二维码', index: 0, id: scope.row.id }">开启、更换绑定二维码</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.GoogleKey"
                      :command="{ title: '显示绑定二维码', index: 1, id: scope.row.id }">显示绑定二维码</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.GoogleKey"
                      :command="{ title: '取消谷歌验证', index: 2, id: scope.row.id }">取消谷歌验证</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <Pagination @current-change="bindList" :total="total"
                    v-model:page-size="searchData.PageSize"  @size-change="refreshClick"
                        v-model:current-page="pageNumber" style="margin-top: 10px;" />
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :title="formData.id ? '编辑' : '新增'" :close-on-click-modal="false" width="500">
      <el-form ref="formRef" label-width="auto" :model="formData" :rules="rules"
        @keypress.native.enter.prevent="submitClick">
        <el-form-item label="用户名" prop="Name">
          <el-input v-model="formData.Name" autocomplete="new-password"/>
        </el-form-item>
        <el-form-item label="密码" prop="Password">
          <el-input type="password" show-password v-model="formData.Password"  autocomplete="new-password"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="formData.Type" placeholder="Select">
            <el-option :key="0" label="普通员工" :value="0" />
            <el-option :key="256" label="管理员" :value="256" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="RoleIds">
          <el-select v-model="formData.RoleIds" multiple placeholder="Select">
            <el-option v-for="role in roleDatas" :key="role.id" :label="role.Caption" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="isBusy || isLoading" @click="submitClick">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogGoogleVisible" :title="googleDialogTitle" :close-on-click-modal="false" width="500">
      <el-form ref="googleFormRef" label-width="auto" :model="googleFormData" :rules="googleRules">
        <el-form-item label="发行方" prop="issuer">
          <el-input v-model="googleFormData.issuer" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogGoogleVisible = false">取消</el-button>
          <el-button type="primary" :loading="isBusy || isLoading" @click="SetUserGoogleKey">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogGoogleCodeVisible" :close-on-click-modal="false">
      <div style="text-align: center;">
        <img :src="setupCode.QrCodeSetupImageUrl" />
      </div>
      <div style="margin: 20px 0;text-align: center;line-height: 30px;">手动绑定<br>{{ setupCode.ManualEntryKey }}</div>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss"></style>